package com.hsnn.medstgmini.trading.pur.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.base.std.service.StdHospInfoManager;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.trading.catalog.model.PurHospcatalog;
import com.hsnn.medstgmini.trading.pur.dao.PurPurPlanDao;
import com.hsnn.medstgmini.trading.pur.model.PurPurPlan;
import com.hsnn.medstgmini.trading.pur.model.form.PurPlanForm;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;
import com.hsnn.medstgmini.util.ParseNumber;
import com.hsnn.medstgmini.util.PinYin;

@Repository("purPurPlanDaoImpl")
public class PurPurPlanDaoImpl implements PurPurPlanDao{
	@Autowired
	private HibernateSqlUtil dao;
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	@Autowired
	private StdHospInfoManager hospInfo;
	/**
	 * 
	 * @category 获取可以制定购物计划列表（医疗机构）
	 * @author 邱磊
	 * @date 2015年7月10日 上午8:28:27
	 * @param page
	 * @return
	 */
	public Pagination getPurHospCatalogList(Pagination page) {
		StringBuffer sql = new StringBuffer()
				.append("select a.hosp_pro_cat_id hospProCatId,a.pro_price proPrice,a.bak_pur_count bakPurCount,")
				.append("  c.drug_code drugCode,c.qualityspec_name qualityspecName,c.form_name formName,c.spec_name specName,c.factor,  ")
			    .append("  c.unit_name unitName,c.material_name materialName,c.pro_price_limit proPriceLimit, ")
			    .append("  c.is_longtime_plan isLongtimePlan,c.goods_code goodsCode,c.proj_name projName, ")
			    .append("  c.prod_compcode prodCompcode,c.prod_compname prodCompname, c.drug_medicine drugMedicine, ")
			    .append("  g.comp_name delcompname,a.del_comp_code delCompCode,c.goods_source goodsSource ")
				.append(" from pur_hospcatalog a")
				.append(" left join base_goods_item c on c.goods_code=a.goods_code ")
				.append(" left join std_compinfo g on g.comp_code=a.del_comp_code and g.status=1 and g.comp_type=2 ")
				.append("   where (a.status=1 and c.status=1 and c.qualityspec_status =1 and c.prod_compstatus=1 and c.proj_status =1 and c.drug_status =1 and c.proj_starttime<=SYSDATE() and c.proj_endtime>=SYSDATE()) ")
				.append(" and a.goods_code not in(select t.goods_code from pur_purplan t where t.hosp_code = :hospCode) ")
				.append(" and a.hosp_code=:hospCode ");
		Map<String, Object> params = new HashMap<String, Object>();
		PurPlanForm form = (PurPlanForm) page.getForm();
		params.put("hospCode", form.getHospCode());
		if (StringUtils.isNotBlank(form.getProjectName())) {
			sql.append(" and c.proj_name like :projectName");
			params.put("projectName", "%"+form.getProjectName()+"%");
		}
		if (StringUtils.isNotBlank(form.getDrugCode())) {
			sql.append(" and c.drug_code=:drugCode");
			params.put("drugCode", form.getDrugCode());
		}
		if (StringUtils.isNotBlank(form.getDrugName())) {
			if (PinYin.isPinYin(form.getDrugName())) {
				sql.append(" and c.qualityspec_name_spel like :drugName");
				params.put("drugName", "%" + form.getDrugName().trim().toUpperCase() + "%");
			} else {
				sql.append(" and c.qualityspec_name like :drugName");
				params.put("drugName", "%" + form.getDrugName().trim() + "%");
			}
		}
		if (StringUtils.isNotBlank(form.getCompName())) {//生产企业
			if (PinYin.isPinYin(form.getCompName())) {
				sql.append(" and c.prod_compname_spel like :compName");
				params.put("compName", "%" + form.getCompName().trim().toUpperCase() + "%");
			} else {
				sql.append(" and c.prod_compname like :compName");
				params.put("compName", "%" + form.getCompName().trim() + "%");
			}
		}
		if (StringUtils.isNotBlank(form.getDelComp())) {//配送企业
			if (PinYin.isPinYin(form.getDelComp().trim())) {
				sql.append(" and g.comp_spel_code like :delComp");
				params.put("delComp", "%"+ form.getDelComp().trim().toUpperCase() + "%");
			} else {
				sql.append(" and g.comp_name like :delComp");
				params.put("delComp", "%" + form.getDelComp().trim()+ "%");
			}
		}
		if (StringUtils.isNotBlank(form.getGoodsSource())) {
			sql.append(" and c.goods_source = :goodsSource");
			params.put("goodsSource", form.getGoodsSource());
		}
		return dao.getSqlPageMapList(sql.toString(), params, page);
	}

	/**
	 * 
	 * @category 加入计划（医疗机构）
	 * @author 邱磊
	 * @date 2015年7月8日 下午6:18:13
	 * @param list
	 */
	public void batchJoinPlan(List<PurPlanForm> list) {
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				PurPlanForm form = list.get(i);
				PurPurPlan data = new PurPurPlan();
				PurHospcatalog info = form.getCatalogInfo();
				BeanUtils.copyProperties(info, data);
				data.setCartId(UUID.randomUUID().toString());
				data.setProCount(ParseNumber.toInteger(form.getBuyNum()));
				data.setJoinPlanTime(new Date());
				data.setJoinPlanUser(form.getJoinPlanUser());
				dao.add(data);
			}
		}
	}

	/**
	 * 
	 * @category 获取已购选购物计划
	 * @author 邱磊
	 * @date 2015年7月10日 上午8:18:44
	 * @param page
	 * @return
	 */
	public Pagination getPurPlanDataList(Pagination page) {
		StringBuffer sql = new StringBuffer()
				.append("select a.cart_id cartId,c.drug_code drugCode,c.qualityspec_name qualityspecName,c.form_name formName,c.spec_name specName,")
				.append("c.factor,c.unit_name unitName,c.material_name materialName,c.prod_compname prodCompname,c.drug_medicine drugMedicine,c.pro_price_limit proPriceLimit,a.pro_price proPrice,c.proj_name projName,")
				.append("g.comp_name delcompname,a.del_comp_code delCompCode,c.is_longtime_plan isLongtimePlan,a.pro_count proCount,c.goods_code goodsCode,")
				.append(" a.join_plan_time joinPlanTime,h.name as username,c.prod_compcode prodCompcode,c.goods_source goodsSource ")
				.append(" from pur_purplan a")
				.append(" left join base_goods_item c on c.goods_code=a.goods_code ")
				.append(" left join std_compinfo g on g.comp_code=a.del_comp_code and g.status=1 and g.comp_type=2 ")
				.append(" left join sys_user h on h.id=a.join_plan_user ")
				.append(" where c.status=1 and c.qualityspec_status =1 and c.prod_compstatus=1 and c.proj_status =1 and c.drug_status =1 and c.proj_starttime<= :startDate and c.proj_endtime>= :endDate   ")
				.append(" and a.hosp_code=:hospCode ");
		Map<String, Object> params = new HashMap<String, Object>();
		PurPlanForm form = (PurPlanForm) page.getForm();
		params.put("hospCode", form.getHospId());
		params.put("startDate", ParseDate.dateToDate(new Date()));
		params.put("endDate", ParseDate.dateToDate(new Date()));
		if (StringUtils.isNotBlank(form.getProjectName())) {
			sql.append(" and c.proj_name like :projectName");
			params.put("projectName", "%"+form.getProjectName()+"%");
		}
		
		if (StringUtils.isNotBlank(form.getDrugCode())) {
			sql.append(" and c.drug_code=:drugCode");
			params.put("drugCode", form.getDrugCode());
		}
		if (StringUtils.isNotBlank(form.getDrugName())) {
			if (PinYin.isPinYin(form.getDrugName())) {
				sql.append(" and c.qualityspec_name_spel like :drugName");
				params.put("drugName", "%"
						+ form.getDrugName().trim().toUpperCase() + "%");
			} else {
				sql.append(" and c.qualityspec_name like :drugName");
				params.put("drugName", "%" + form.getDrugName().trim() + "%");
			}
		}
		if (StringUtils.isNotBlank(form.getCompName())) {
			if (PinYin.isPinYin(form.getCompName())) {
				sql.append(" and c.prod_compname_spel like :compName");
				params.put("compName", "%" + form.getCompName().trim().toUpperCase() + "%");
			} else {
				sql.append(" and c.prod_compname like :compName");
				params.put("compName", "%" + form.getCompName().trim() + "%");
			}
		}
		if (StringUtils.isNotBlank(form.getDelComp())) {
			if (PinYin.isPinYin(form.getDelComp().trim())) {
				sql.append(" and g.comp_spel_code like :delComp");
				params.put("delComp", "%"+ form.getDelComp().trim().toUpperCase() + "%");
			} else {
				sql.append(" and g.comp_name like :delComp");
				params.put("delComp", "%" + form.getDelComp().trim()+ "%");
			}
		}
		if (StringUtils.isNotBlank(form.getGoodsSource())) {
			sql.append(" and c.goods_source = :goodsSource");
			params.put("goodsSource", form.getGoodsSource());
		}
		if (0 == form.getMain()) {
			sql.append(" and a.join_plan_user=:joinPlanUser");
			params.put("joinPlanUser", form.getJoinPlanUser());
		}
		if (StringUtils.isNotBlank(form.getUserName())){
			sql.append(" and h.name like :userName");
			params.put("userName", "%" +form.getUserName() + "%");
		}
		
		sql.append(" order by a.join_plan_time desc ");
		return dao.getSqlNOPageMapList(sql.toString(), params, page);
	}

	/**
	 * 
	 * @category 删除（医疗机构）
	 * @author 邱磊
	 * @date 2015年7月10日 上午8:17:50
	 * @param list
	 */
	public void batchDelete(List<PurPlanForm> list) {
		if (null != list && list.size() > 0) {
			String sql = "DELETE from pur_purplan where cart_id in (:cartId)";
			Map<String, Object> params = new HashMap<String, Object>();
			List<String> plist = new ArrayList<String>();
			for (int i = 0; i < list.size(); i++) {
				PurPlanForm form = list.get(i);
				plist.add(form.getCartId());
			}
			params.put("cartId", plist);
			dao.executeSql(sql, params);
		}
	}

	/**
	 * 
	 * @category 保存（医疗机构）
	 * @author 邱磊
	 * @date 2015年7月10日 上午8:18:18
	 * @param list
	 */
	public void batchSave(List<PurPlanForm> list) {
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				PurPlanForm form = list.get(i);
				String sql = "update pur_purplan set pro_count=:proCount ,pro_price= :proPrice , upd_datetime=SYSDATE() , upd_user=:updUser where cart_id=:cartId";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("cartId", form.getCartId());
				params.put("proCount", form.getBuyNum());
				params.put("updUser", form.getUpdUser());
				params.put("proPrice", form.getProPrice());
				dao.executeSql(sql, params);
			}
		}
	}

	/**
	 * 
	 * @category 根据ID获取已勾选目录ID
	 * @author 邱磊
	 * @date 2015年7月17日 下午4:12:51
	 * @param id
	 * @return
	 */
	public PurHospcatalog getCatalogInfoById(String id) {
		return (PurHospcatalog) dao.getUniquerResult(PurHospcatalog.class, id);
	}
	
	/**
	 * 
	 * @category 获取购物计划数量
	 * @author wangbing
	 * @date 2015年7月17日 下午4:12:51
	 * @param id
	 * @return
	 */
	@Override
	public int getPlanCount(String hospCode){
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sql = new StringBuffer()
		.append(" SELECT COUNT(*) FROM pur_purplan a  LEFT JOIN base_goods_item c  ON c.goods_code=a.goods_code ")
		.append(" WHERE c.status=1 AND c.qualityspec_status =1 AND c.prod_compstatus=1 AND c.proj_status =1 	")
		.append(" AND c.drug_status =1  AND c.proj_starttime<= ? AND c.proj_endtime>= ? AND a.hosp_code=?		");
		Query query = session.createSQLQuery(sql.toString());
		query.setParameter(0, ParseDate.dateToDate(new Date()));
		query.setParameter(1, ParseDate.dateToDate(new Date()));
		query.setParameter(2, hospCode);
		return Integer.parseInt(query.uniqueResult().toString());
	}


	@Override
	public Pagination getHisRecordAmount(Pagination page) {
		String sql  = " select base_amount,non_base_amount from his_record_amount where hosp_code=:hospCode ";
		HashMap<String , Object> params = new HashMap<String, Object>();
		params.put("hospCode", page.getConditions().get("hospCode"));
		page.setRows(dao.getSqlMapUniqueResult(sql, params)); 
		if (null == page.getRows()){
			StringBuffer sbsql = new StringBuffer()
			.append("insert into his_record_amount")
			.append(" select UUID(),a.hosp_code,a.hosp_name,a.hosp_spel_code,a.status,a.hosp_classify,a.area_id,b.area_name,")
			.append(" b.ar_shortname,b.ar_fullname,0.00,0.00,:updUser,SYSDATE() from std_hospinfo a")
			.append(" left join dic_area b on a.area_id=b.area_id")
			.append(" where a.hosp_code=:hospCode");
			Map<String, Object> pm = new HashMap<String, Object>();
			pm.put("updUser", page.getConditions().get("userId"));
			pm.put("hospCode", page.getConditions().get("hospCode"));
			dao.executeSql(sbsql.toString(), pm);
			page.setRows(dao.getSqlMapUniqueResult(sql, params));
		}
		return page;
	}

	
	@Override
	public void updateHisRecordAmount(Pagination page) {
		SysUser user = (SysUser) page.getForm() ;
		HospInfo hosp = (HospInfo)user.getInfo();
		String sql = " update his_record_amount set base_amount=:baseAmount ,non_base_amount =:nonBaseAmount, upd_user = :updUser ,upd_datetime = now()  where hosp_code=:hospCode";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("baseAmount", page.getConditions().get("baseAllAmount"));
		params.put("nonBaseAmount",page.getConditions().get("nonBaseAllAmount"));
		params.put("updUser",user.getId());
		params.put("hospCode",hosp.getHospCode());
		dao.executeSql(sql, params);
	}
}
